<template>
    <div class="admin-seeds-container">
        <div class="page-header">
            <div class="action-buttons">
                <el-button type="primary" icon="el-icon-plus" @click="drawer = true">新增花种</el-button>
                <el-button type="danger" icon="el-icon-delete" :disabled="multipleSelection.length === 0">批量删除</el-button>
                <el-button type="warning" icon="el-icon-sold-out" :disabled="multipleSelection.length === 0">停售花种</el-button>
                <el-button type="success" icon="el-icon-shopping-cart-2" :disabled="multipleSelection.length === 0">起售花种</el-button>
            </div>
        </div>

        <!-- 搜索和筛选区域 -->
        <div class="filter-container">
            <el-input
                placeholder="搜索花种名称"
                v-model="searchKeyword"
                class="search-input"
                clearable
                prefix-icon="el-icon-search"
                @keyup.enter.native="handleSearch"
            ></el-input>
            <el-select v-model="categoryFilter" placeholder="花种类别" clearable class="filter-select">
                <el-option label="全部类别" value=""></el-option>
                <el-option label="圣诞节" value="圣诞节"></el-option>
                <el-option label="情人节" value="情人节"></el-option>
                <el-option label="新年" value="新年"></el-option>
                <el-option label="其他传统节日" value="其他传统节日"></el-option>
            </el-select>
            <el-select v-model="colorFilter" placeholder="花色筛选" clearable class="filter-select">
                <el-option label="全部颜色" value=""></el-option>
                <el-option label="粉色系" value="粉色"></el-option>
                <el-option label="蓝色系" value="蓝色"></el-option>
                <el-option label="黄色系" value="黄色"></el-option>
                <el-option label="绿色系" value="绿色"></el-option>
                <el-option label="白色系" value="白色"></el-option>
            </el-select>
            <el-button type="primary" @click="handleSearch" icon="el-icon-search">搜索</el-button>
            <el-button @click="resetSearch" icon="el-icon-refresh">重置</el-button>
        </div>

        <!-- 花种列表 -->
        <el-card class="table-card">
            <el-table 
                :data="filteredTableData" 
                style="width: 100%"
                border
                v-loading="loading"
                element-loading-text="加载中..."
                @selection-change="handleSelectionChange"
                stripe
            >
                <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column type="expand">
                <template slot-scope="props">
                        <el-card class="expand-card">
                            <div class="expand-container">
                                <div class="expand-image">
                                    <el-image 
                                        :src="props.row.flowerPhoto" 
                                        fit="cover"
                                        style="width: 200px; height: 200px;"
                                        :preview-src-list="[props.row.flowerPhoto]">
                                        <div slot="error" class="image-slot">
                                            <i class="el-icon-picture-outline"></i>
                                        </div>
                                    </el-image>
                                </div>
                                <div class="expand-details">
                                    <el-descriptions title="基本信息" :column="2" border>
                                        <el-descriptions-item label="花种名称">{{ props.row.name }}</el-descriptions-item>
                                        <el-descriptions-item label="花种ID">{{ props.row.flowerId }}</el-descriptions-item>
                                        <el-descriptions-item label="花语">{{ props.row.menaning }}</el-descriptions-item>
                                        <el-descriptions-item label="价格">¥{{ props.row.price }}</el-descriptions-item>
                                        <el-descriptions-item label="库存量">{{ props.row.stock }}</el-descriptions-item>
                                        <el-descriptions-item label="成花颜色">{{ props.row.color }}</el-descriptions-item>
                                        <el-descriptions-item label="养护难度">{{ props.row.difficulty }}</el-descriptions-item>
                                        <el-descriptions-item label="适宜季节">{{ props.row.season }}</el-descriptions-item>
                                        <el-descriptions-item label="特殊属性">{{ props.row.specialAttribute }}</el-descriptions-item>
                                        <el-descriptions-item label="商品分类">{{ props.row.category }}</el-descriptions-item>
                                        <el-descriptions-item label="标签" :span="2">{{ props.row.tags }}</el-descriptions-item>
                                        <el-descriptions-item label="商品描述" :span="2">{{ props.row.introduction }}</el-descriptions-item>
                                    </el-descriptions>
                                </div>
                            </div>
                        </el-card>
                    </template>
                </el-table-column>
                <el-table-column label="花种ID" prop="flowerId" width="100" align="center"></el-table-column>
                <el-table-column label="图片" width="90" align="center">
                    <template slot-scope="scope">
                        <el-image 
                            :src="scope.row.flowerPhoto" 
                            style="width: 60px; height: 60px;"
                            :preview-src-list="[scope.row.flowerPhoto]">
                            <div slot="error" class="image-slot">
                                <i class="el-icon-picture-outline"></i>
                            </div>
                        </el-image>
                </template>
            </el-table-column>
                <el-table-column label="花种名称" prop="name" min-width="120"></el-table-column>
                <el-table-column label="价格" prop="price" width="100" align="center">
                    <template slot-scope="scope">
                        <span>¥{{ scope.row.price }}</span>
                    </template>
            </el-table-column>
                <el-table-column label="库存" prop="stock" width="90" align="center"></el-table-column>
                <el-table-column label="花语" prop="menaning" min-width="150" show-overflow-tooltip></el-table-column>
                <el-table-column label="颜色" prop="color" width="100" align="center">
                    <template slot-scope="scope">
                        <el-tag :type="getColorType(scope.row.color)">{{ scope.row.color }}</el-tag>
                    </template>
            </el-table-column>
                <el-table-column label="销售状态" width="100" align="center">
                    <template slot-scope="scope">
                        <el-tag :type="scope.row.status ? 'success' : 'info'">
                            {{ scope.row.status ? '在售' : '停售' }}
                        </el-tag>
                    </template>
            </el-table-column>
                <el-table-column label="操作" width="180" fixed="right">
                <template slot-scope="scope">
                        <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button size="mini" type="danger" icon="el-icon-delete" @click="confirmDelete(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        </el-card>

        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page.sync="currentPage"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="filteredTableData.length">
            </el-pagination>
        </div>

        <!-- 新增/编辑花种抽屉 -->
        <el-drawer 
            :title="isEdit ? '编辑花种' : '新增花种'" 
            :visible.sync="drawer" 
            direction="rtl" 
            size="60%" 
            :destroy-on-close="false" 
            custom-class="seed-drawer"
        >
            <div class="drawer-content">
                <div class="drawer-header">
                    <h3>{{ isEdit ? '编辑花种信息' : '新增花种' }}</h3>
                </div>

                <el-form ref="form" :model="form" label-width="120px" class="seed-form">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="花种图片" class="upload-container">
                                <el-upload 
                                    class="avatar-uploader" 
                                    action="/file/upload"
                                    :show-file-list="false" 
                                    :on-success="handleAvatarSuccess"
                                    :before-upload="beforeUpload"
                                >
                                    <img v-if="form.flowerPhoto" :src="form.flowerPhoto" class="avatar">
                                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="花种名称" required>
                                <el-input v-model="form.name" placeholder="请输入花种名称"></el-input>
                    </el-form-item>
                            <el-form-item label="花种寓意" required>
                                <el-input v-model="form.menaning" placeholder="请输入花种寓意"></el-input>
                    </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="花种价格" required>
                                <el-input-number v-model="form.price" :precision="2" :step="0.1" :min="0" style="width: 100%"></el-input-number>
                    </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="花种库存" required>
                                <el-input-number v-model="form.stock" :min="0" :step="1" style="width: 100%"></el-input-number>
                    </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="成花颜色" required>
                                <el-select v-model="form.color" placeholder="请选择大致颜色区域" style="width: 100%">
                            <el-option label="粉色系" value="粉色"></el-option>
                            <el-option label="蓝色系" value="蓝色"></el-option>
                            <el-option label="黄色系" value="黄色"></el-option>
                            <el-option label="绿色系" value="绿色"></el-option>
                            <el-option label="白色系" value="白色"></el-option>
                        </el-select>
                    </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="养护难度" required>
                                <el-select v-model="form.difficulty" placeholder="请选择大致养护难度" style="width: 100%">
                            <el-option label="新手友好型" value="新手友好型"></el-option>
                            <el-option label="中等维护需求" value="中等维护需求"></el-option>
                            <el-option label="高级养护需求" value="高级养护需求"></el-option>
                        </el-select>
                    </el-form-item>
                        </el-col>
                    </el-row>

                    <el-form-item label="花期" required>
                        <el-col :span="11">
                            <el-date-picker 
                                type="month" 
                                placeholder="开始月份" 
                                v-model="form.date1"
                                style="width: 100%;"
                                value-format="yyyy-MM">
                            </el-date-picker>
                        </el-col>
                        <el-col class="line" :span="2" style="text-align: center">-</el-col>
                        <el-col :span="11">
                            <el-date-picker 
                                type="month" 
                                placeholder="结束月份" 
                                v-model="form.date2"
                                style="width: 100%;"
                                value-format="yyyy-MM">
                            </el-date-picker>
                        </el-col>
                    </el-form-item>

                    <el-form-item label="起售状态">
                        <el-switch 
                            v-model="form.status"
                            active-color="#13ce66"
                            inactive-color="#ff4949"
                            active-text="起售"
                            inactive-text="停售">
                        </el-switch>
                    </el-form-item>

                    <el-form-item label="特殊属性">
                        <el-checkbox-group v-model="form.specialAttribute" class="checkbox-group">
                            <el-checkbox label="吸附甲醛花卉" name="specialAttribute"></el-checkbox>
                            <el-checkbox label="抗污染花卉" name="specialAttribute"></el-checkbox>
                            <el-checkbox label="耐阴花卉" name="specialAttribute"></el-checkbox>
                            <el-checkbox label="耐旱花卉" name="specialAttribute"></el-checkbox>
                            <el-checkbox label="耐寒花卉" name="specialAttribute"></el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>

                    <el-form-item label="标签">
                        <el-checkbox-group v-model="form.tags" class="checkbox-group">
                            <el-checkbox label="爱情与浪漫" name="tags"></el-checkbox>
                            <el-checkbox label="友谊与感谢" name="tags"></el-checkbox>
                            <el-checkbox label="祝福与好运" name="tags"></el-checkbox>
                            <el-checkbox label="长寿与健康" name="tags"></el-checkbox>
                            <el-checkbox label="荣誉与成就" name="tags"></el-checkbox>
                            <el-checkbox label="纪念与哀悼" name="tags"></el-checkbox>
                            <el-checkbox label="家庭与亲情" name="tags"></el-checkbox>
                            <el-checkbox label="勇气与力量" name="tags"></el-checkbox>
                            <el-checkbox label="智慧与学习" name="tags"></el-checkbox>
                            <el-checkbox label="和平与和谐" name="tags"></el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>

                    <el-form-item label="适应季节">
                        <el-checkbox-group v-model="form.season" class="checkbox-group">
                            <el-checkbox label="春天" name="season"></el-checkbox>
                            <el-checkbox label="夏天" name="season"></el-checkbox>
                            <el-checkbox label="秋天" name="season"></el-checkbox>
                            <el-checkbox label="冬天" name="season"></el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>

                    <el-form-item label="花种类别" required>
                        <el-radio-group v-model="form.category">
                            <el-radio label="圣诞节"></el-radio>
                            <el-radio label="情人节"></el-radio>
                            <el-radio label="新年"></el-radio>
                            <el-radio label="其他传统节日"></el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="成花介绍" required>
                        <el-input type="textarea" v-model="form.introduction" :rows="4" placeholder="请输入花种详细介绍"></el-input>
                    </el-form-item>

                    <el-form-item class="form-buttons">
                        <el-button type="primary" @click="onSubmit" :loading="submitLoading">{{ isEdit ? '保存' : '创建' }}</el-button>
                        <el-button @click="No">重置</el-button>
                        <el-button @click="drawer = false">取消</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-drawer>

        <!-- 删除确认对话框 -->
        <el-dialog
            title="确认删除"
            :visible.sync="deleteDialogVisible"
            width="30%">
            <span>确定要删除"{{ currentRow ? currentRow.name : '' }}"吗？此操作不可逆。</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="deleteDialogVisible = false">取消</el-button>
                <el-button type="danger" @click="handleDelete">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            drawer: false,
            isEdit: false,
            loading: false,
            submitLoading: false,
            tableData: [],
            multipleSelection: [],
            searchKeyword: '',
            categoryFilter: '',
            colorFilter: '',
            currentPage: 1,
            pageSize: 10,
            deleteDialogVisible: false,
            currentRow: null,
            currentIndex: null,
            form: {
                season: [], // 确保这是一个数组
                flowerPhoto: '',
                specialAttribute: [],
                tags: [],
                name: '',
                menaning: '',
                price: '',
                stock: '',
                color: '',
                difficulty: '',
                date1: '',
                date2: '',
                status: true,
                category: '',
                introduction: ''
            }
        }
    },
    computed: {
        filteredTableData() {
            let result = [...this.tableData];
            
            // 搜索关键字过滤
            if (this.searchKeyword) {
                const keyword = this.searchKeyword.toLowerCase();
                result = result.filter(item => 
                    (item.name && item.name.toLowerCase().includes(keyword)) || 
                    (item.menaning && item.menaning.toLowerCase().includes(keyword))
                );
            }
            
            // 类别过滤
            if (this.categoryFilter) {
                result = result.filter(item => item.category === this.categoryFilter);
            }
            
            // 颜色过滤
            if (this.colorFilter) {
                result = result.filter(item => item.color === this.colorFilter);
            }
            
            return result;
        }
    },
    created() {
        // 请求分页查询数据
        this.load()
    },
    methods: {
        // 获取花种数据
        load() {
            this.loading = true;
            this.request.get("/flowers/list").then(res => {
                console.log(res);
                this.tableData = res.data;
                this.loading = false;
            }).catch(() => {
                this.loading = false;
            })
        },
        
        // 提交表单
        onSubmit() {
            this.submitLoading = true;
            this.request.post("/flowers/create", this.form).then(res => {
                console.log(res);
                this.$message.success(this.isEdit ? '花种更新成功' : '花种添加成功');
                this.drawer = false;
                this.load(); // 重新加载数据
                this.submitLoading = false;
            }).catch(err => {
                console.error('提交失败:', err);
                this.$message.error('操作失败，请重试');
                this.submitLoading = false;
            })
        },
        
        // 重置表单
        No() {
            this.$refs.form.resetFields();
            this.form = {
                season: [],
                flowerPhoto: '',
                specialAttribute: [],
                tags: [],
                name: '',
                menaning: '',
                price: '',
                stock: '',
                color: '',
                difficulty: '',
                date1: '',
                date2: '',
                status: true,
                category: '',
                introduction: ''
            };
        },
        
        // 编辑花种
        handleEdit(index, row) {
            this.isEdit = true;
            this.form = JSON.parse(JSON.stringify(row)); // 深拷贝避免直接修改表格数据
            this.drawer = true;
        },
        
        // 确认删除对话框
        confirmDelete(index, row) {
            this.currentRow = row;
            this.currentIndex = index;
            this.deleteDialogVisible = true;
        },
        
        // 删除花种
        handleDelete() {
            if (this.currentRow) {
                console.log('删除:', this.currentRow);
                // 这里应该是删除API调用
                this.$message.success('删除成功');
                this.deleteDialogVisible = false;
                this.currentRow = null;
                this.currentIndex = null;
                this.load(); // 重新加载数据
            }
        },
        
        // 头像上传成功
        handleImageSuccess(res) {
            this.form.flowerPhoto = res;
        },
        
        // 多选变化
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        
        // 搜索
        handleSearch() {
            this.currentPage = 1;
        },
        
        // 重置搜索
        resetSearch() {
            this.searchKeyword = '';
            this.categoryFilter = '';
            this.colorFilter = '';
            this.currentPage = 1;
        },
        
        // 改变每页大小
        handleSizeChange(val) {
            this.pageSize = val;
        },
        
        // 改变页码
        handleCurrentChange(val) {
            this.currentPage = val;
        },
        
        // 获取颜色标签类型
        getColorType(color) {
            const colorMap = {
                '粉色': 'danger',
                '蓝色': 'primary',
                '黄色': 'warning',
                '绿色': 'success',
                '白色': 'info'
            };
            return colorMap[color] || 'info';
        },
        
        // 上传图片前的验证
        beforeUpload(file) {
            const isImage = file.type.startsWith('image/');
            if (!isImage) {
                this.$message.error('只能上传图片文件！');
                return false;
            }
            return true;
        }
    }
}
</script>

<style scoped>
.admin-seeds-container {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: calc(100vh - 120px);
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.page-header h2 {
    margin: 0;
    font-size: 22px;
    color: #303133;
}

.action-buttons {
    display: flex;
    gap: 10px;
}

.filter-container {
    display: flex;
    margin-bottom: 20px;
    align-items: center;
    flex-wrap: wrap;
    background-color: #fff;
    padding: 15px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.search-input {
    width: 300px;
    margin-right: 15px;
    margin-bottom: 10px;
}

.filter-select {
    width: 180px;
    margin-right: 15px;
    margin-bottom: 10px;
}

.table-card {
    margin-bottom: 20px;
}

.pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
    padding: 15px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.expand-container {
    display: flex;
    gap: 20px;
}

.expand-image {
    flex-shrink: 0;
}

.expand-details {
    flex-grow: 1;
}

.expand-card {
    margin: 10px;
    box-shadow: none !important;
}

.drawer-content {
    padding: 20px;
}

.drawer-header {
    margin-bottom: 20px;
}

.drawer-header h3 {
    margin: 0;
    font-size: 18px;
    color: #303133;
}

.seed-form {
    padding: 0 10px;
}

.upload-container {
    display: flex;
    justify-content: center;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.checkbox-group {
    display: flex;
    flex-wrap: wrap;
}

.checkbox-group .el-checkbox {
    margin-right: 15px;
    margin-bottom: 10px;
}

.form-buttons {
    margin-top: 30px;
}

.demo-table-expand {
    font-size: 0;
}

.demo-table-expand label {
    width: 90px;
    color: #99a9bf;
}

.demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
}

::v-deep .seed-drawer .el-drawer__header {
    margin-bottom: 0;
    padding: 20px;
    border-bottom: 1px solid #e6e6e6;
    font-size: 18px;
    font-weight: bold;
}

::v-deep .el-form-item__label {
    font-weight: 500;
}

::v-deep .el-input-number .el-input__inner {
    text-align: left;
}

::v-deep .el-table {
    margin-bottom: 0;
}

.image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: #f5f7fa;
    color: #909399;
}
</style>